<template>
  <div class="car-appointment-list">
    <div class="header">
      <h3>预约记录</h3>
      <el-button v-if="isUser" type="primary" size="small" @click="handleAddAppointment">
        <el-icon><Plus /></el-icon>预约看车
      </el-button>
    </div>

    <!-- 调试信息 -->
    <div v-if="showDebugInfo" class="debug-info">
      <h4>用户信息调试:</h4>
      <pre>{{ userInfoDebug }}</pre>
      <el-button size="small" @click="reloadUserInfo">重新加载用户信息</el-button>
    </div>

    <div v-loading="loading">
      <el-empty v-if="appointments.length === 0" description="暂无预约记录" />
      
      <el-table v-else :data="appointments" style="width: 100%">
        <el-table-column prop="userId" label="用户ID" width="80" v-if="isAdmin" />
        <el-table-column prop="carId" label="车辆ID" width="80" v-if="isAdmin" />
        <el-table-column prop="dealerId" label="经销商ID" width="100" v-if="isAdmin" />
        <el-table-column label="预约时间" min-width="150">
          <template #default="scope">
            {{ formatDate(scope.row.appointmentTime) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="note" label="备注" min-width="150" />
        <el-table-column label="创建时间" min-width="150" v-if="isAdmin">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button 
              v-if="canEdit(scope.row)" 
              link type="primary" 
              @click="handleEditAppointment(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              v-if="canCancel(scope.row)" 
              link type="danger" 
              @click="handleCancelAppointment(scope.row)"
            >
              取消预约
            </el-button>
            <el-button 
              v-if="canUpdateStatus(scope.row) && isAdmin" 
              link type="warning"
              @click="handleUpdateStatus(scope.row)"
            >
              更新状态
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加/编辑预约对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="form" ref="formRef" label-width="100px" :rules="rules">
        <el-form-item v-if="isAdmin" label="用户ID" prop="userId">
          <el-input v-model.number="form.userId" placeholder="请输入用户ID" :disabled="true" />
        </el-form-item>
        <el-form-item v-else label="用户ID" prop="userId" v-show="isUserLoggedIn">
          <el-input v-model.number="form.userId" placeholder="请输入用户ID" disabled />
        </el-form-item>
        
        <!-- 未登录用户信息 -->
        <template v-if="!isUserLoggedIn">
          <el-form-item label="姓名" prop="guestName">
            <el-input v-model="form.guestName" placeholder="请输入您的姓名" />
          </el-form-item>
          <el-form-item label="手机号" prop="guestPhone">
            <el-input v-model="form.guestPhone" placeholder="请输入您的手机号" />
          </el-form-item>
        </template>
        
        <el-form-item v-if="carId === null && isAdmin" label="车辆ID" prop="carId">
          <el-input v-model.number="form.carId" placeholder="请输入车辆ID" />
        </el-form-item>
        <el-form-item label="经销商" prop="dealerId">
          <el-select v-model="form.dealerId" placeholder="请选择经销商">
            <el-option label="经销商1" value="1" />
            <el-option label="经销商2" value="2" />
            <el-option label="经销商3" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="预约时间" prop="appointmentTime">
          <el-date-picker
            v-model="form.appointmentTime"
            type="datetime"
            placeholder="选择预约日期时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabled-date="disabledDate"
            :disabled-hours="disabledHours"
          />
        </el-form-item>
        <el-form-item v-show="false" v-if="isAdmin" label="状态" prop="status">
          <el-select 
            v-model="form.status" 
            placeholder="请选择状态"
            :disabled="!isEdit && !isAdmin" 
          >
            <el-option label="待确认" value="pending" />
            <el-option label="已确认" value="confirmed" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input v-model="form.note" type="textarea" rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 更新状态对话框 -->
    <el-dialog
      title="更新预约状态"
      v-model="statusDialogVisible"
      width="400px"
    >
      <el-form :model="statusForm" label-width="100px">
        <el-form-item label="当前状态">
          <el-tag :type="getStatusType(statusForm.currentStatus)">
            {{ getStatusText(statusForm.currentStatus) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新状态" prop="newStatus">
          <el-select v-model="statusForm.newStatus" placeholder="请选择新状态">
            <el-option label="待确认" value="pending" />
            <el-option label="已确认" value="confirmed" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="statusDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitStatusUpdate">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, defineProps, defineEmits } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getAppointmentsByCarId,
  getAppointmentsByUserId,
  getAllAppointments,
  addAppointment, 
  updateAppointment, 
  deleteAppointment,
  updateAppointmentStatus
} from '@/api/appointment'
import { createGuestUserAndAppointment } from '@/api/user' // 导入创建临时用户的API
import { Plus } from '@element-plus/icons-vue'

const props = defineProps({
  carId: {
    type: [Number, String],
    default: null
  },
  userId: {
    type: [Number, String],
    default: null
  },
  isAdmin: {
    type: Boolean,
    default: false
  },
  isUser: {
    type: Boolean,
    default: false
  },
  showDebugInfo: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['refresh'])

const loading = ref(false)
const appointments = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('预约看车')
const isEdit = ref(false)
const statusDialogVisible = ref(false)
const userInfoDebug = ref('未获取到用户信息')

// 表单数据
const form = ref({
  id: undefined,
  userId: props.userId || (props.isAdmin ? '' : getUserId()),
  carId: props.carId || '',
  dealerId: '',
  appointmentTime: '',
  status: 'pending',
  note: '',
  guestName: '', // 未登录用户的姓名
  guestPhone: '' // 未登录用户的手机号
})

// 状态表单
const statusForm = ref({
  id: '',
  currentStatus: '',
  newStatus: ''
})

// 表单规则
const rules = {
  userId: [
    { required: true, message: '请输入用户ID', trigger: 'blur' },
    { type: 'number', message: '用户ID必须为数字', trigger: 'blur', transform: val => Number(val) }
  ],
  carId: [
    { required: true, message: '请输入车辆ID', trigger: 'blur' },
    { type: 'number', message: '车辆ID必须为数字', trigger: 'blur', transform: val => Number(val) }
  ],
  dealerId: [
    { required: true, message: '请选择经销商', trigger: 'change' }
  ],
  appointmentTime: [
    { required: true, message: '请选择预约时间', trigger: 'change' }
  ],
  guestName: [
    { required: true, message: '请输入您的姓名', trigger: 'blur' }
  ],
  guestPhone: [
    { required: true, message: '请输入您的手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ]
}

// 获取用户ID（从localStorage获取）
const getUserId = () => {
  try {
    const userInfoStr = localStorage.getItem('userInfo')
    if (userInfoStr) {
      const userInfo = JSON.parse(userInfoStr)
      if (userInfo && userInfo.userId) {
        return userInfo.userId
      }
    }
    // 如果没有获取到，返回null
    console.warn('未从localStorage获取到用户ID')
    return null
  } catch (error) {
    console.error('获取用户ID失败:', error)
    return null
  }
}

// 判断用户是否已登录
const isUserLoggedIn = computed(() => {
  return !!getUserId();
})

// 获取预约记录
const fetchAppointments = async () => {
  loading.value = true
  try {
    let response
    const currentUserId = getUserId();
    console.log('当前用户ID:', currentUserId);
    
    if (props.carId) {
      console.log('按车辆ID查询预约:', props.carId);
      response = await getAppointmentsByCarId(props.carId)
    } else if (props.userId && !props.isAdmin) {
      console.log('按用户ID查询预约:', props.userId);
      response = await getAppointmentsByUserId(props.userId)
    } else if (props.isAdmin) {
      console.log('管理员查询所有预约');
      response = await getAllAppointments()
    } else {
      console.log('普通用户查询自己的预约:', currentUserId);
      response = await getAppointmentsByUserId(currentUserId)
    }
    console.log('获取到的预约数据:', response);
    appointments.value = response || []
  } catch (error) {
    console.error('获取预约记录失败:', error)
    ElMessage.error('获取预约记录失败')
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case '0':
    case 'pending': 
      return 'info'
    case '1':
    case 'confirmed': 
      return 'success'
    case '2':
    case 'completed': 
      return 'primary'
    case '3':
    case 'cancelled': 
      return 'danger'
    default: 
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case '0':
    case 'pending': 
      return '待确认'
    case '1':
    case 'confirmed': 
      return '已确认'
    case '2':
    case 'completed': 
      return '已完成'
    case '3':
    case 'cancelled': 
      return '已取消'
    default: 
      return '未知状态'
  }
}

// 是否可以编辑预约
const canEdit = (appointment) => {
  // 待确认状态不可编辑，管理员除外
  const pendingStatus = appointment.status === 'pending' || appointment.status === '0';
  return !pendingStatus || props.isAdmin;
}

// 是否可以取消预约
const canCancel = (appointment) => {
  return appointment.status === 'pending' || 
         appointment.status === 'confirmed' || 
         appointment.status === '0' || 
         appointment.status === '1';
}

// 是否可以更新状态
const canUpdateStatus = (appointment) => {
  return (appointment.status !== 'cancelled' && 
          appointment.status !== 'completed' &&
          appointment.status !== '3' && 
          appointment.status !== '2');
}

// 禁用日期（今天之前的日期）
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7 // 禁用今天之前的日期
}

// 禁用时间（工作时间外）
const disabledHours = () => {
  return Array.from({ length: 24 }).map((_, i) => i).filter(h => h < 9 || h > 18)
}

// 添加预约
const handleAddAppointment = () => {
  isEdit.value = false
  dialogTitle.value = '预约看车'
  const currentUserId = getUserId();
  form.value = {
    id: undefined,
    userId: props.userId || (props.isAdmin ? currentUserId : currentUserId),
    carId: props.carId || '',
    dealerId: '',
    appointmentTime: '',
    status: 'pending',
    note: '',
    guestName: '',
    guestPhone: ''
  }
  dialogVisible.value = true
}

// 编辑预约
const handleEditAppointment = (appointment) => {
  isEdit.value = true
  dialogTitle.value = '编辑预约'
  form.value = { ...appointment }
  dialogVisible.value = true
}

// 取消预约
const handleCancelAppointment = (appointment) => {
  ElMessageBox.confirm('确定要取消这个预约吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 如果是管理员，直接更新状态为已取消
      if (props.isAdmin) {
        await updateAppointmentStatus(appointment.id, 'cancelled')
      } else {
        // 如果是用户，直接删除预约
        await deleteAppointment(appointment.id)
      }
      ElMessage.success('预约已取消')
      fetchAppointments()
      emit('refresh')
    } catch (error) {
      console.error('取消预约失败:', error)
      ElMessage.error('取消预约失败')
    }
  }).catch(() => {})
}

// 更新状态
const handleUpdateStatus = (appointment) => {
  statusForm.value = {
    id: appointment.id,
    currentStatus: appointment.status,
    newStatus: ''
  }
  statusDialogVisible.value = true
}

// 提交状态更新
const submitStatusUpdate = async () => {
  if (!statusForm.value.newStatus) {
    ElMessage.warning('请选择新状态')
    return
  }

  try {
    await updateAppointmentStatus(statusForm.value.id, statusForm.value.newStatus)
    ElMessage.success('状态更新成功')
    statusDialogVisible.value = false
    fetchAppointments()
    emit('refresh')
  } catch (error) {
    console.error('状态更新失败:', error)
    ElMessage.error('状态更新失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  const formRef = ref(null)
  
  try {
    // 针对表单规则进行验证
    if (!isUserLoggedIn.value && (!form.value.guestName || !form.value.guestPhone)) {
      ElMessage.warning('请填写姓名和手机号');
      return;
    }

    if (isEdit.value) {
      // 编辑模式
      await updateAppointment(form.value)
      ElMessage.success('更新成功')
    } else {
      // 新增模式
      if (isUserLoggedIn.value) {
        // 已登录用户直接创建预约
        await addAppointment(form.value)
        ElMessage.success('预约成功')
      } else {
        // 未登录用户，先创建临时用户再创建预约
        const guestData = {
          name: form.value.guestName,
          phone: form.value.guestPhone,
          carId: form.value.carId ? Number(form.value.carId) : null,
          dealerId: form.value.dealerId ? Number(form.value.dealerId) : null,
          appointmentTime: formatDateForBackend(form.value.appointmentTime),
          note: form.value.note || ''
        }
        
        // 添加类型检查，确保数据类型正确
        if (typeof guestData.carId !== 'number' || isNaN(guestData.carId)) {
          ElMessage.error('车辆ID格式不正确');
          return;
        }

        if (typeof guestData.dealerId !== 'number' || isNaN(guestData.dealerId)) {
          ElMessage.error('经销商ID格式不正确');
          return;
        }

        if (!guestData.appointmentTime) {
          ElMessage.error('预约时间不能为空');
          return;
        }
        
        // 打印发送的数据，便于调试
        console.log('发送临时用户预约数据:', guestData);
        
        const response = await createGuestUserAndAppointment(guestData)
        console.log('临时用户预约响应:', response);
        
        if (response && response.success) {
          ElMessage.success('预约成功')
        } else {
          throw new Error((response && response.message) || '预约失败')
        }
      }
    }
    
    dialogVisible.value = false
    fetchAppointments()
    emit('refresh')
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(error.message || '操作失败')
  }
}

// 重新加载用户信息
const reloadUserInfo = () => {
  try {
    const userInfoStr = localStorage.getItem('userInfo')
    userInfoDebug.value = userInfoStr || '未获取到用户信息'
    ElMessage.success('重新加载用户信息成功')
    // 刷新预约列表
    fetchAppointments()
  } catch (error) {
    console.error('重新加载用户信息失败:', error)
    ElMessage.error('重新加载用户信息失败')
  }
}

// 格式化日期为后端接受的格式
const formatDateForBackend = (dateStr) => {
  if (!dateStr) return null;
  
  try {
    // 检查是否已经是Date对象
    if (dateStr instanceof Date) {
      return dateStr.toISOString();
    }
    
    // 将前端的日期字符串解析为Date对象
    // 如果日期字符串包含"T"，表示它可能已经是ISO格式
    if (typeof dateStr === 'string' && dateStr.includes('T')) {
      return dateStr; // 可能已经是ISO格式，直接返回
    }
    
    // 尝试解析日期字符串
    const date = new Date(dateStr);
    if (isNaN(date.getTime())) {
      console.error('无效的日期:', dateStr);
      return null; // 返回null表示无效日期
    }
    
    // 格式化为ISO字符串，Java可以正确解析这种格式
    return date.toISOString();
  } catch (error) {
    console.error('日期格式化错误:', error);
    return null;
  }
}

onMounted(() => {
  // 加载调试信息
  if (props.showDebugInfo) {
    const userInfoStr = localStorage.getItem('userInfo')
    userInfoDebug.value = userInfoStr || '未获取到用户信息'
  }
  
  fetchAppointments()
})
</script>

<style scoped>
.car-appointment-list {
  padding: 10px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h3 {
  margin: 0;
  font-size: 18px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.debug-info {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 12px;
}

.debug-info h4 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 14px;
}

.debug-info pre {
  margin: 0 0 10px 0;
  white-space: pre-wrap;
  max-height: 200px;
  overflow: auto;
}
</style> 